<?php
include_once('config/config.php');

$LoginAdmin = checkAuth();

if($_POST)
{
  $action = $_POST['action'] ?? '';

  // 请求部门数据
  if($action == 'depid')
  {
    $DepData = all("SELECT * FROM `pre_department` ORDER BY `id` DESC");

    if($DepData)
    {
      echo json_encode(['code' => 1,'msg' => '查询部门数据成功','data' => $DepData]);
      exit;
    }else{
      echo json_encode(['code' => 0,'msg' => '暂无数据','data' => null]);
      exit;
    }
  }

  // 请求职位数据
  if($action == 'jobid')
  {
    $depid = $_POST['depid'] ?? 0;

    $JobData = all("SELECT * FROM `pre_job` WHERE `depid` = '$depid'");

    if($JobData)
    {
      echo json_encode(['code' => 1,'msg' => '查询职位数据成功','data' => $JobData]);
      exit;
    }else{
      echo json_encode(['code' => 0,'msg' => '暂无数据','data' => null]);
      exit;
    }
  }

  // 处理表单提交数据

  // 把提交过来的数据重新组装成一个新的数组
  $data = [
    'name' => $_POST['name'],
    'mobile' => $_POST['mobile'],
    'email' => $_POST['email'],
    'sex' => $_POST['sex'],
    'address' => $_POST['address'],
    'depid' => $_POST['depid'],
    'jobid' => $_POST['jobid'],
    'createtime' => time()
  ];

  // 处理地区数据
  if(!empty($_POST['code']))
  {
    $code = $_POST['code'];

    // 获取ID路径
    $pathStr = find("SELECT `parentpath` FROM `pre_region` WHERE `code` = '$code'");

    if(!$pathStr)
    {
      showMsg('所选地区不存在');
    }

    // 字符串转成数组
    $pathArr = explode(',',$pathStr['parentpath']);

    // 赋值
    $data['province'] = $pathArr[0] ?? null;
    $data['city'] = $pathArr[1] ?? null;
    $data['district'] = $pathArr[2] ?? null;
  }

  // 处理头像数据
  $avatar = build_upload('avatar');

  if($avatar['code'] === 0)
  {
    showMsg($avatar['msg']);
  }

  $data['avatar'] = $avatar['data'];

  // 插入数据表
  $result = add('person',$data);

  if($result['code'] === 0)
  {
    @is_file(ltrim($data['avatar'],'/')) && @unlink(ltrim($data['avatar'],'/'));
    echo $result['msg'];
    exit;
  }else{
    showMsg($result['msg'],'personList.php');
  }

}
?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <?php include_once('common/meta.php'); ?>
    <link rel="stylesheet" href="/assets/lib/city-picker/city-picker.css">
  </head>
  <style>
    .region{
      position: relative;
      width: 530px;
    }

    .address{
      margin-top: 55px;
    }

    input[type="file"]{
      display: none;
    }

    label[for="avatar"]
    {
      width: 200px;
    }
  </style>
  <body>
    <?php include_once('common/header.php');?>
    
    <?php include_once('common/menu.php') ?>>

    <div class="content">
        <div class="header">
            <h1 class="page-title">添加员工</h1>
        </div>
        <ul class="breadcrumb">
            <li><a href="personList.php">personList</a> <span class="divider">/</span></li>
            <li class="active">personAdd</li>
        </ul>

        <div class="container-fluid">
            <div class="row-fluid">
                    
                <div class="btn-toolbar">
                    <button class="btn btn-primary" onClick="location='personList.php'"><i class="icon-list"></i> 员工列表</button>
                  <div class="btn-group">
                  </div>
                </div>

                <div class="well">
                    <div id="myTabContent" class="tab-content">
                      <div class="tab-pane active in" id="home">
                        <form method="post" enctype="multipart/form-data">
                            
                          <label>员工姓名</label>
                          <input type="text" name="name" placeholder="请输入员工姓名" class="input-xxlarge">

                          <label>手机号</label>
                          <input type="text" name="mobile" placeholder="请输入手机号" class="input-xxlarge">
                          
                          <label>邮箱</label>
                          <input type="email" name="email" placeholder="请输入邮箱" class="input-xxlarge">

                          <label>性别</label>
                          <select name="sex" class="input-xlarge">
                            <option value="0">保密</option>
                            <option value="1">男</option>
                            <option value="2">女</option>
                          </select>

                          <div class="region">
                            <label>选择地区</label>
                            <input type="text" data-toggle="city-picker" id="region" value="" class="input-xxlarge">
                            <input type="hidden" name="code" id="code">
                          </div>
                          

                          <div class="address">
                            <label>地址</label>
                            <input type="text" name="address" placeholder="请输入地址" class="input-xxlarge">
                          </div>

                          <label>部门</label>
                          <select name="depid" class="input-xlarge">
                            <option value="0">请选择</option>
                          </select>

                          <label>职位</label>
                          <select name="jobid" class="input-xlarge">
                            <option value="0">请选择</option>
                          </select>

                          <label>头像</label>
                          <label for="avatar">
                            <img src="/assets/images/upload.png" id="upload" alt="">
                          </label>
                          <input type="file" name="avatar" id="avatar" class="input-xlarge">

                          <label></label>
                          <input class="btn btn-primary" type="submit" value="提交" />
                        </form>
                      </div>
                  </div>
                </div>
                
                <?php include_once('common/footer.php'); ?>
                    
            </div>
        </div>
    </div>
    
  </body>
</html>

<?php include_once('common/script.php'); ?>
<script src="/assets/lib/city-picker/city-picker.data.min.js"></script>
<script src="/assets/lib/city-picker/city-picker.min.js"></script>

<script>
  // 图片预览
  $('#avatar').change(function(){
    let file = $(this)[0].files[0];
    
    if(file)
    {
      let reader = new FileReader();

      reader.readAsDataURL(file)

      // 事件
      reader.onload = function()
      {
        $('#upload').attr('src',reader.result);
      }
    }
  });

  // 查询部门
  (function(){
    $.ajax({
      type:'post',
      url:'personAdd.php',
      data:{
        action:'depid'
      },
      dataType:'json',
      success:function(res)
      {
        if(res.code === 1)
        {
          let temp = '';

          for(let item of res.data)
          {
            temp += `<option value="${item.id}">${item.name}</option>`
          }

          $('select[name="depid"]').html(temp);

          let depid = res.data[0].id ? res.data[0].id : 0

          getJobData(depid)
        }
      }
    });
  })();


  function getJobData(depid)
  {
    $.ajax({
      type:'post',
      url:'personAdd.php',
      data:{
        action:'jobid',
        depid
      },
      dataType:'json',
      success:function(res)
      {
        if(res.code === 1)
        {
          let temp = '';

          for(let item of res.data)
          {
            temp += `<option value="${item.id}">${item.name}</option>`
          }

          $('select[name="jobid"]').html(temp);
        }
      }
    });
  }

  // 选择部门需要更新
  $('select[name="depid"]').change(function(){
      let depid = $(this).val()

      getJobData(depid)
  });

  // 选择地区
  $("#region").on("cp:updated", function() {
    var citypicker = $(this).data("citypicker");
    var code = citypicker.getCode("district") || citypicker.getCode("city") || citypicker.getCode("province");
    $("#code").val(code);
  });
  
</script>